import { stringify } from 'querystring';
import { history } from 'umi';
import { authorizations, getImageCode } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';
import { setToken } from '@/utils/auth'
import Store from '@/utils/store'

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
    captchaData: {
      captcha_image_content: '',
    },
  },
  effects: {
    *login({ payload }, { call, put }) {
      const { data } = yield call(authorizations, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: data,
      });

      yield setToken(`${data.meta.token_type} ${data.meta.access_token}`)
      yield Store.saveLocal('loginInfoSMP', data)

      if (data) {
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        message.success('🎉 🎉 🎉  登录成功！');
        let { redirect } = params;

        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (window.routerBase !== '/') {
              redirect = redirect.replace(window.routerBase, '/');
            }

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }

        history.replace(redirect || '/');
      }
    },

    *getCaptCha(action, { call, put }) {
      const { data } = yield call(getImageCode);
      yield put({
        type: 'save',
        payload: { captchaData: data },
      });
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority('admin');
      return { ...state, status: payload.status, type: payload.type };
    },
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    setup({ dispatch }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/user/login') {
          dispatch({
            type: 'getCaptCha',
          });
        }
      });
    },
  },
};
export default Model;
